
import { v4 as uuidv4 } from 'uuid';

/**
 * 数组转换成options的树
 * 即[value: 0, label: '节点', children: []]
 * @param {*} list
 * @param {*} parentId
 * @param {*} label
 * @returns 返回为全分支
 */
function initTree(list, parentId, label) {
	const data = list.filter((e) => e.parentId === parentId);
	const tree = [];
	for (let i = 0; i < data.length; i++) {
		const item = {
			value: data[i].id,
			label: data[i][label],
		};
		const children = initTree(list, data[i].id, label);
		if (children.length > 0) {
			item.children = children;
		}
		tree.push(item);
	}

	return tree;
}
/**
 * 基本数组转树---parentId转children
 * @param {*} data
 * @param {*} arr
 * @param {*} id
 * @returns
 */
function createTree(data, arr, id) {
  const filtersList = arr.filter(e => e.parentId === id);
  data.children = filtersList;
  data.children = data.children.map(e => {
    e = createTree(e, arr, e.id);
    if (e.children.length > 0) {
      return e;
    } else {
      delete e.children
      return e
    }

  });
  return data;
}
/**
 * 给定树结构唯一的row-key
 * @param {*} tree
 * @param {*} count
 * @param {*} r
 * @returns
 */
function readNodes(tree, count, r) {
  for (const data of tree) {
    data.sort = uuidv4()
      if (data.versionList) {
        readNodes(data.versionList, count, r)
      }
  }
  return r
}
/**
 * 遍历树，修改树内指定节点kv
 * @param {*} tree
 * @param {*} func
 * @returns
 */
function treeFind(tree, func) {
  for (const data of tree) {
    if (func(data)) {
      data.disabled = true
      return tree
    }
      if (data.children) {
      const res = treeFind(data.children, func)
      if (res) return res
    }
  }
  return null
}

/**
 * 返回children>0的，即获取节点的parentId进行过滤
 * @param {*} arr
 * @returns
 */
function flagChildren(arr) {
  // 如果children大于0返回
  let result = []
  for (const item of arr) {
    const res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据作为第一层级的填充
    delete res.children
    if (item.children instanceof Array && item.children.length > 0) { // 如果当前children为数组并且长度大于0，才可进入flag()方法
      result.push(item)
      result = result.concat(flagChildren(item.children))
    }
  }
  return result
}
/**
 * 遍历分支节点,返回包含当前节点
 * @param {*} arr
 * @returns
 */
function flag(arr) {
  let result = []
  for (const item of arr) {
    const res = JSON.parse(JSON.stringify(item)) // 先克隆一份数据作为第一层级的填充
    delete res.children
    result.push(res)
    if (item.children instanceof Array && item.children.length > 0) { // 如果当前children为数组并且长度大于0，才可进入flag()方法
      result = result.concat(flag(item.children))
    }
  }
  return result
}

export default {
  initTree,
  createTree,
  readNodes,
  treeFind,
  flagChildren,
  flag
}
